<?php


namespace App\Services;

use App\Models\ClassGrade;
use App\Models\ClassStudent;
use App\Models\Course;

class ClassGradeService  extends BaseService
{
    /**
     * 根据名称获取名称
     * @param $name
     * @return User|null|Model
     */
    public function getByName($name){
        return ClassGrade::query()->where('name',$name)->where('deleted_at',null)->first();
    }
    /**
     * 根据学校id班级id获取学生数量
     * @param $school_id
     * @param $class_grades_id
     * @return User|null|Model
     */
    public function getClassGradeStudentNum($school_id,$class_grades_id){
        $query = ClassStudent::leftJoin('users', 'users.id', '=', 'class_students.users_id');
        return $query->where('class_students.school_id',$school_id)->where('class_grades_id',$class_grades_id)
            ->where('users.type',0)
            ->distinct('users_id')->count();
    }
    /**
     * 获取列表
     * @return
     */
    public function listClassGrade($school_id,$name, $page,$limit,$sort,$order) {
        $query = ClassGrade::leftJoin('schools', 'schools.id', '=', 'class_grades.school_id')
            ->select('class_grades.*','schools.name as school_name');
        if(!empty($name)){
            $query->where('class_grades.name','like',"%$name%");
        }
        if(!empty($school_id)){
            $query->where('school_id',$school_id);
        }

        return $query->orderBy($sort,$order)->paginate($limit, ['*'], 'page', $page);
    }
    /**
     * 学校课程
     * @return
     */
    public function classCourse($class_grades_id) {
        $query = Course::leftJoin('school_class_courses', 'school_class_courses.course_id', '=', 'courses.id')
            ->select('courses.id','courses.name','school_class_courses.school_id','school_class_courses.class_grades_id');
        if(!empty($class_grades_id)){
            $query->where('class_grades_id',$class_grades_id);
        }
        return $query->get();
    }



}
